package ivalidator

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"github.com/go-playground/locales/zh"
	"github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"

	vt "github.com/go-playground/validator/v10/translations/zh"
	log "github.com/sirupsen/logrus"
)

//验证框架验证器实例
var validate *validator.Validate

//验证消息国际化通用翻译器
var translator ut.Translator

func Validate() *validator.Validate {
	base.Check(validate)
	return validate
}

type ValidatorStarter struct {
	base.BaseStarter
}

func (s *ValidatorStarter) Init(ctx base.StarterContext) {
	validate = validator.New() //创建验证器
	zh := zh.New()             //中文翻译器创建
	uni := ut.New(zh, zh)      //通用翻译器创建UniversalTranslator
	//获取通用中文翻译器
	translator, found := uni.GetTranslator("zh")
	if found { //如果获取到就注册到验证器
		err := vt.RegisterDefaultTranslations(validate, translator)
		if err != nil {
			log.Error(err)
		}
	} else { //获取不到就输出错误提示
		log.Error("Not found translator: zh")
	}
}

func (s *ValidatorStarter) Setup(ctx base.StarterContext) {}
func (s *ValidatorStarter) Start(ctx base.StarterContext) {}
func (s *ValidatorStarter) Stop(ctx base.StarterContext)  {}

func ValidateStruct(s interface{}) (err error) {
	//验证
	err = Validate().Struct(s)
	if err != nil {
		if _, ok := err.(*validator.InvalidValidationError); ok {
			log.Error(err)
		}
		errs, ok := err.(validator.ValidationErrors)
		if ok {
			for _, err := range errs {
				log.Error(err.Translate(translator))
			}
		}
		return err
	}
	return nil
}
